//
//  CutoutCollageViewController.swift
//  SwiftPhtotEdit
//
//  Created by aw031 on 13/10/2025.
//

import UIKit
import SnapKit
class CutoutCollageViewController: UIViewController {
    
    // MARK: - IBOutlets
    lazy var backView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.red
        view.layer.masksToBounds = true
        return view
    }()
    
    
    lazy var imageBgV: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.red
        view.layer.masksToBounds = true
        return view
    }()
    
    
    
    lazy var imageView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFit
//        imageView.image = KImage("")
        return imgView
    }()
    
    
    lazy var autoCutBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("auto", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        
        btn.normalImage = UIImage.colorConversionImage(with: .lightText)
        btn.selectImage = UIImage.colorConversionImage(with: .lightGray)

        btn.setCustomImage(UIImage.init(systemName: "star"))
        btn.setCustomImage(UIImage.init(systemName: "star.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
     
        btn.addTarget(self, action: #selector(autocutBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var lassoCutBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("lassoCut", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        
        btn.normalImage = UIImage.colorConversionImage(with: .lightText)
        btn.selectImage = UIImage.colorConversionImage(with: .lightGray)

        btn.setCustomImage(UIImage.init(systemName: "star.hexagon"))
        btn.setCustomImage(UIImage.init(systemName: "star.hexagon.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(lassoCutBtnClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var eraseBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("erase", for: .normal)
        btn.titleLabel?.font = FontScale(20)
        btn.normalImage = UIImage.colorConversionImage(with: .lightText)
        btn.selectImage = UIImage.colorConversionImage(with: .lightGray)

        btn.setCustomImage(UIImage.init(systemName: "pencil.tip.crop.circle"))
        btn.setCustomImage(UIImage.init(systemName: "pencil.tip.crop.circle.fill") ,for: .selected)
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(eraseBtnClick), for: .touchUpInside)
        return btn
    }()
    
    
    lazy var photoBtn: CustomButton = {
        let btn = CustomButton(type: .custom)
        btn.setTitle("photo", for: .normal)
        btn.titleLabel?.font = FontScale(20)

        btn.setCustomImage(UIImage.init(systemName: "photo.stack"))
        btn.setTitleColor(UIColor.init(hex: "55555"), for: .normal)
        btn.setTitleColor(UIColor.init(hex: "000000"), for: .selected)
        
        btn.addTarget(self, action: #selector(photoClickUpInside), for: .touchUpInside)
        return btn
    }()
//    @IBOutlet weak var autoCutBtn: UIButton!
//    @IBOutlet weak var lassoCutBtn: UIButton!
//    @IBOutlet weak var eraseBtn: UIButton!
    
    
    // MARK: - Properties
    var erasePath: UIBezierPath?
    var undoStack: [UIBezierPath] = []
    var restoreStack: [UIBezierPath] = []
    var originalMask: UIImage?
    var sourceImage: UIImage?
    var lastTouchPoint: CGPoint = .zero
    var eraserIconView: UIImageView?
    var cutImage: UIImage?
    
    var isRestoring: Bool = false
    var isEdit: Bool = false
    var taskCount: Int = 0
    
    var isPinching: Bool = false
    
    
    // 闭包属性
    var backBtnClick: ClickBlock?
    var saveBtnClick: ImageBlock?
//    
//    // 需要获取当前视图控制器
//    weak var viewController: UIViewController?
//    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        // Do any additional setup after loading the view.
        
        self.setUpDataUI()
        // 开启用户交互
        self.imageView.isUserInteractionEnabled = true
        
        // 添加捏合手势
        let pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
        self.imageView.addGestureRecognizer(pinch)
        
        // 添加拖拽手势（仅支持双指平移）
        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        pan.minimumNumberOfTouches = 2
        pan.maximumNumberOfTouches = 2
        self.imageView.addGestureRecognizer(pan)
    }
    
    
    
    func setUpDataUI() {
        // MARK: - IBOutlets
        view.addSubview(backView)
        backView.addSubview(imageBgV)
        imageBgV.addSubview(imageView)

        backView.addSubview(autoCutBtn)
        backView.addSubview(lassoCutBtn)
        backView.addSubview(eraseBtn)
        backView.addSubview(photoBtn)

        backView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        imageBgV.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(300)
        }
        
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        
        autoCutBtn.snp.makeConstraints { make in
            make.top.equalTo(imageBgV.snp.bottom).offset(30)
            make.leading.equalTo(16)
            make.height.equalTo(60)
        }
          
        
        
        lassoCutBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(autoCutBtn.snp.trailing).offset(16)
        }
          
        
        eraseBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(lassoCutBtn.snp.trailing).offset(16)
        }
        
        
        photoBtn.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(autoCutBtn)
            make.leading.equalTo(eraseBtn.snp.trailing).offset(16)
            make.trailing.equalTo(-16)
        }
          
        
    }
    
    func setImage(_ image: UIImage) {
        self.sourceImage = image
        self.imageView.image = image
        
        self.autocutBtnClick(self.autoCutBtn)
    }
    
    // MARK: - Button Actions
    @objc func autocutBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        
        lassoCutBtn.isSelected = false
        eraseBtn.isSelected = false
        isEdit = false
        if let eraserIconView = self.eraserIconView {
            eraserIconView.isHidden = true
        }
        
//        autoCutImgView.image = UIImage(named: sender.isSelected ? "make_autocut_sel" : "make_autocut_nor")
//        lassoCutImgView.image = UIImage(named: "make_lassocut_nor")
//        eraseImgView.image = UIImage(named: "make_erase_nor")
//        autoCutLabel.textColor = UIColor(hexString: sender.isSelected ? "#9684FF" : "#141415")
//        lassoCutLabel.textColor = UIColor(hexString: "#141415")
//        eraseLabel.textColor = UIColor(hexString: "#141415")
//        
        if sender.isSelected {
            if let cutImage = self.cutImage {
                self.imageView.image = cutImage
                self.originalMask = cutImage
                
                self.resetTouchData()
            } else {
                self.loadResultData(self.sourceImage)
            }
        } else {
            self.imageView.image = self.sourceImage
            self.originalMask = self.sourceImage
            
            self.resetTouchData()
        }
    }
    
    @objc func lassoCutBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        eraseBtn.isSelected = false
        isEdit = sender.isSelected
        
        if let eraserIconView = self.eraserIconView {
            eraserIconView.isHidden = !sender.isSelected
        }
        
//        lassoCutImgView.image = UIImage(named: sender.isSelected ? "make_lassocut_sel" : "make_lassocut_nor")
//        eraseImgView.image = UIImage(named: "make_erase_nor")
//        lassoCutLabel.textColor = UIColor(hexString: sender.isSelected ? "#9684FF" : "#141415")
//        eraseLabel.textColor = UIColor(hexString: "#141415")
        
        if !sender.isSelected { return }
        
        self.isRestoring = true
        self.originalMask = self.imageView.image
        
        if self.eraserIconView == nil {
            self.eraserIconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
            self.eraserIconView?.image = UIImage(named: "make_cut_line")
            self.eraserIconView?.center = self.imageView.center
            if let eraserIconView = self.eraserIconView {
                self.imageView.addSubview(eraserIconView)
            }
        }
    }
    
    @objc func eraseBtnClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        lassoCutBtn.isSelected = false
        isEdit = sender.isSelected
        
        if let eraserIconView = self.eraserIconView {
            eraserIconView.isHidden = !sender.isSelected
        }
        
//        lassoCutImgView.image = UIImage(named: "make_lassocut_nor")
//        eraseImgView.image = UIImage(named: sender.isSelected ? "make_erase_sel" : "make_erase_nor")
//        lassoCutLabel.textColor = UIColor(hexString: "#141415")
//        eraseLabel.textColor = UIColor(hexString: sender.isSelected ? "#9684FF" : "#141415")
        
        if !sender.isSelected { return }
        
        self.isRestoring = false
        self.originalMask = self.imageView.image
        
        if self.eraserIconView == nil {
            self.eraserIconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
            self.eraserIconView?.image = UIImage(named: "make_cut_line")
            self.eraserIconView?.center = self.imageView.center
            if let eraserIconView = self.eraserIconView {
                self.imageView.addSubview(eraserIconView)
            }
        }
    }
    
    @IBAction func backBtnClick(_ sender: UIButton) {
        self.backView.removeFromSuperview()
        
        self.backBtnClick?()
    }
    
    @IBAction func saveBtnClick(_ sender: UIButton) {
        // 注意：这里需要替换为实际的 PurchaseManager 和 CommonClass 实现
        /*
         if !PurchaseManager.shared.isMember && CommonClass.showCutout() {
         let vc = PremiumEditionController()
         if let currentVC = CommonClass.currentViewController() {
         currentVC.navigationController?.pushViewController(vc, animated: true)
         }
         } else {
         if self.imageView.image != nil {
         CommonClass.updateCutout(true)
         }
         
         self.saveBtnClick?(self.imageView.image)
         }
         */
        
        // 临时实现 - 直接保存
        self.saveBtnClick?(self.imageView.image)
    }
    
    // MARK: - Touch Handling
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isEdit || isPinching { return }
        
        guard let touch = touches.first else { return }
        let touchPointInView = touch.location(in: self.imageView)
        
        guard let img = self.sourceImage else { return }
        
        let imageSize = img.size
        let imageViewSize = self.imageView.bounds.size
        let scale = min(imageViewSize.width / imageSize.width, imageViewSize.height / imageSize.height)
        let fittedImageSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
        let x = (imageViewSize.width - fittedImageSize.width) / 2.0
        let y = (imageViewSize.height - fittedImageSize.height) / 2.0
        
        let currentPoint = CGPoint(
            x: (touchPointInView.x - x) * (imageSize.width / fittedImageSize.width),
            y: (touchPointInView.y - y) * (imageSize.height / fittedImageSize.height)
        )
        
        if let eraserIconView = self.eraserIconView {
            eraserIconView.center = touchPointInView
        }
        
        guard let originalMask = self.originalMask else { return }
        
        if self.erasePath == nil {
            self.erasePath = UIBezierPath()
            self.erasePath?.lineWidth = 5.0
            self.erasePath?.lineCapStyle = .round
        }
        
        if self.lastTouchPoint == .zero {
            self.erasePath?.move(to: currentPoint)
        } else {
            let midPoint = CGPoint(
                x: (self.lastTouchPoint.x + currentPoint.x) / 2.0,
                y: (self.lastTouchPoint.y + currentPoint.y) / 2.0
            )
            self.erasePath?.addQuadCurve(to: midPoint, controlPoint: self.lastTouchPoint)
        }
        
        self.lastTouchPoint = currentPoint
        
        self.renderMask()
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !isEdit || isPinching { return }
        
        if let erasePath = self.erasePath, !erasePath.isEmpty {
            if self.isRestoring {
                if self.restoreStack.isEmpty {
                    self.restoreStack = []
                }
                self.restoreStack.append(erasePath.copy() as! UIBezierPath)
                // 恢复操作，清除擦除轨迹
                self.undoStack.removeAll()
            } else {
                if self.undoStack.isEmpty {
                    self.undoStack = []
                }
                self.undoStack.append(erasePath.copy() as! UIBezierPath)
                // 擦除操作，清除恢复轨迹
                self.restoreStack.removeAll()
            }
        }
        self.erasePath = nil
        self.lastTouchPoint = .zero
    }
    
    // MARK: - Mask Rendering
    func renderMask() {
        guard let sourceImage = self.sourceImage else { return }
        
        UIGraphicsBeginImageContextWithOptions(sourceImage.size, false, 0)
        defer { UIGraphicsEndImageContext() }
        
        self.originalMask?.draw(at: .zero)
        
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.saveGState()
        
        ctx.setLineCap(.round)
        ctx.setLineWidth(20.0)
        
        if self.isRestoring {
            for path in self.restoreStack {
                ctx.saveGState()
                ctx.addPath(path.cgPath)
                ctx.replacePathWithStrokedPath()
                ctx.clip()
                sourceImage.draw(at: .zero)
                ctx.restoreGState()
            }
            if let erasePath = self.erasePath {
                ctx.saveGState()
                ctx.addPath(erasePath.cgPath)
                ctx.replacePathWithStrokedPath()
                ctx.clip()
                sourceImage.draw(at: .zero)
                ctx.restoreGState()
            }
        } else {
            ctx.setBlendMode(.clear)
            ctx.setStrokeColor(UIColor.clear.cgColor)
            let paths = self.undoStack
            for path in paths {
                ctx.addPath(path.cgPath)
                ctx.strokePath()
            }
            if let erasePath = self.erasePath {
                ctx.addPath(erasePath.cgPath)
                ctx.strokePath()
            }
        }
        
        ctx.restoreGState()
        
        if let result = UIGraphicsGetImageFromCurrentImageContext() {
            self.imageView.image = result
            self.originalMask = result
        }
    }
    
    func resetTouchData() {
        self.undoStack.removeAll()
        self.restoreStack.removeAll()
        self.erasePath = nil
        self.lastTouchPoint = .zero
    }
    
    // MARK: - Album
    @objc func photoClickUpInside() {
        // 需要实现权限检查和相册访问
        /*
         PermissionManager.checkPhotoLibraryPermission()
         let imagePickerController = UIImagePickerController()
         imagePickerController.delegate = self
         imagePickerController.allowsEditing = false
         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
         imagePickerController.sourceType = .photoLibrary
         self.viewController?.present(imagePickerController, animated: true)
         }
         */
        PhotoTools.shared.showPhotoAndCameraPicker(in: self, isPhoto: true, resultHandler:{ [weak self] img in
            //            self??.pushBackgroundEditVC(image: img,isPhoto: true) { image in
            //                self?.changeBackground(selectStyle: 1, colors: [], backImage: image)
            //            }
            //            if let image = info[.originalImage] as? UIImage {
            self?.sourceImage = img
            self?.imageView.image = img
            self?.autocutBtnClick(self!.autoCutBtn)
            //            }
        })
        
    }
    
    // MARK: - UIImagePickerControllerDelegate
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
            
        self.navigationController?.popViewController(animated: true)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        if let image = info[.originalImage] as? UIImage {
            self.sourceImage = image
            self.imageView.image = image
            self.autocutBtnClick(self.autoCutBtn)
        }
    }
    
    // MARK: - Network Requests
    func loadResultData(_ image: UIImage?) {
        guard let image = image else {
            // PSProgressHUD.showToast("The image cannot be empty", view: self)
            return
        }
        
        // PSProgressHUD.show(in: self)
        
        // 需要实现网络请求逻辑
        /*
         let request = UploadImageRequest()
         request.image = image
         
         request.startWithCompletionBlock(success: { [weak self] request in
         guard let self = self else { return }
         if let responseDict = request.responseObject as? [String: Any],
         let code = responseDict["code"] as? NSNumber, code == 0,
         let data = responseDict["data"] as? [String: Any],
         let filePath = data["filePath"] as? String {
         self.createTask(filePath)
         } else {
         // PSProgressHUD.hide(in: self)
         // PSProgressHUD.showToast("Please try again later", view: self)
         }
         }, failure: { [weak self] request, message in
         guard let self = self else { return }
         // PSProgressHUD.hide(in: self)
         // PSProgressHUD.showToast("Please try again later", view: self)
         })
         */
    }
    
    func createTask(_ filePath: String) {
        // 实现创建任务的网络请求
    }
    
    func taskStatus(_ taskId: String) {
        // 实现任务状态查询的网络请求
    }
    
    // MARK: - Gesture Handlers
    @objc func handlePinch(_ pinch: UIPinchGestureRecognizer) {
        switch pinch.state {
        case .began, .changed:
            self.isPinching = true
        case .ended, .cancelled:
            self.isPinching = false
        default:
            break
        }
        
        // 在当前 transform 上叠加缩放
        if let view = pinch.view {
            view.transform = view.transform.scaledBy(x: pinch.scale, y: pinch.scale)
        }
        pinch.scale = 1.0 // 重置 scale，避免叠加过度
        
        self.resetTouchData()
    }
    
    @objc func handlePan(_ pan: UIPanGestureRecognizer) {
        guard let piece = pan.view else { return }
        let translation = pan.translation(in: piece.superview)
        
        switch pan.state {
        case .began, .changed:
            piece.center = CGPoint(x: piece.center.x + translation.x, y: piece.center.y + translation.y)
            pan.setTranslation(.zero, in: piece.superview)
            self.isPinching = true // 复用 isPinching 标志禁止绘制
        case .ended, .cancelled:
            self.isPinching = false
        default:
            break
        }
        self.resetTouchData()
    }
}


